<template>
  <el-form
    :model="form"
    ref="form"
    class="edit-bot-form"
    :rules="rules"
    @submit.native.prevent
    @keyup.enter.native="onSave"
    v-loading="loading"
  >
    <el-form-item prop="name" :label="$t('custom.botStore.name')">
      <el-input
        v-model="form.name"
        :maxlength="70"
        show-word-limit
        :placeholder="$t('custom.botStore.enterName')"
      ></el-input>
    </el-form-item>
    <el-form-item prop="roleIdList" :label="$t('custom.reports.role')">
      <el-select
        v-model="form.roleIdList"
        filterable
        clearable
        multiple
        collapse-tags
        default-first-option
        style="width: 100%"
        :placeholder="$t('custom.reports.role')"
      >
        <el-option
          v-for="(item, index) in roleOptions"
          :key="index"
          :value="item.roleId"
          :label="item.name"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="tagList" :label="$t('custom.reports.tag')">
      <el-select
        v-model="form.tagList"
        filterable
        clearable
        multiple
        allow-create
        collapse-tags
        default-first-option
        :placeholder="$t('custom.reports.tag')"
        style="width: 100%"
      >
        <el-option
          v-for="(item, index) in tags"
          :key="index"
          :label="item.name"
          :value="item.name"
        >
            <div style="display: flex;justify-content:space-between;">
                        <ZTooltip :content="item.name"
                           :line="1"
                          placement="top">
                            <span style="flex:1">{{ item.name }}</span>
                        </ZTooltip>
                        <span>
                          <el-button 
                                       style="float: right;font-size: 14px;margin-top: 3px;margin-left: 10px;"
                                       size='mini'
                                       type="text"
                                       @click.stop="deleteTag(item)">
                              <i class="cuifont icon_delete"
                                 style="font-size:14px;color:#CCC"></i>
                            </el-button>
                        </span>
            </div>
      </el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="description" :label="$t('custom.botStore.description')">
      <el-input
        v-model="form.description"
        type="textarea"
        :maxlength="500"
        :rows="3"
        show-word-limit
        @keyup.enter.native.stop
        :placeholder="$t('custom.botStore.description')"
      ></el-input>
    </el-form-item>

    <el-form-item class="text-right">
      <el-button
        type="text"
        @click="moreEditVisible = true"
        v-if="$hasPermission('sys:bots:moreedit')"
        size="small"
        >{{ $t('custom.reports.moreedit') }}</el-button
      >
      <el-button size="small" type="primary" @click="onSave">{{
        $t('custom.botStore.save')
      }}</el-button>
    </el-form-item>

    <el-dialog
      width="470px"
      :title="$t('custom.reports.moreedit')"
      :visible.sync="moreEditVisible"
      append-to-body
      custom-class="more-dialog"
      destroy-on-close
    >
      <el-form
        :model="form"
        v-loading="moreLoading"
        ref="moreForm"
        class="more-edit-dialog-form"
        :rules="rules"
        @submit.native.prevent
        @keyup.enter.native="onSave"
        label-position="top"
      >
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item prop="classification" label="Template Type">
              <el-select
                v-model="form.classification"
                :placeholder="$t('custom.bots.edit.classification')"
                style="width: 100%"
              >
                <el-option
                  v-for="item in classOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="businessType"
              :label="$t('custom.dataset.businessType')"
            >
              <el-select
                v-model="form.businessType"
                :placeholder="$t('custom.dataset.businessType')"
                style="width: 100%"
                :disabled="
                  !$hasPermission('sys:tenant:model:allowtomanagesystemmodel')
                "
              >
                <el-option
                  v-for="item in businessTypes"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status" :label="$t('custom.dataset.status')">
              <el-select
                v-model="form.status"
                :placeholder="$t('custom.dataset.status')"
                style="width: 100%"
                :disabled="
                  !$hasPermission('sys:tenant:model:allowtomanagesystemmodel')
                "
              >
                <el-option
                  v-for="item in statusList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="tenantCode"
              :label="$t('custom.dataset.tenantCode')"
            >
              <SelectClientId
                v-model="form.tenantCode"
                :disabled="
                  form.businessType === 'Template' ||
                  form.businessType === 'MSPbots Internal'
                "
                :width="100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="da" :label="$t('custom.report.da')">
              <el-select
                v-model="form.da"
                clearable
                filterable
                :placeholder="$t('custom.report.da')"
                style="width: 100%"
              >
                <el-option
                  v-for="items in users"
                  :key="items.id"
                  :label="items.realname"
                  :value="items.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="po" :label="$t('custom.report.po')">
              <el-select
                v-model="form.po"
                clearable
                filterable
                :placeholder="$t('custom.report.po')"
                style="width: 100%"
              >
                <el-option
                  v-for="items in users"
                  :key="items.id"
                  :label="items.realname"
                  :value="items.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="jiraNumber"
              :label="$t('custom.reports.jiraNumber')"
            >
              <el-input
                v-model="form.jiraNumber"
                type="text"
                style="width: 100%"
                rows="3"
                :placeholder="$t('custom.reports.jiraNumber')"
              >
                <JiraNumberLink slot="suffix" :jiraNumber="form.jiraNumber" />
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="shared" :label="$t('custom.dataset.shared')">
              <el-switch
                v-model="form.shared"
                active-color="#007bff"
                inactive-color="#dcdfe6"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="applyTenant"
              v-if="$hasPermission('sys:bot:defaultinstall')"
              :label="$t('custom.dataset.defaultInstall')"
            >
              <el-switch
                v-model="form.applyTenant"
                active-color="#007bff"
                inactive-color="#dcdfe6"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template slot="footer">
        <el-button @click="moreEditVisible = false" size="small">{{
          $t('Cancel')
        }}</el-button>
        <el-button type="primary" @click="onSave" size="small">{{
          $t('Save')
        }}</el-button>
      </template>
    </el-dialog>
  </el-form>
</template>

<script>
import useErrorMessage from '@/components/storybook/hooks/useErrorMessage'
import { intersectionBy, set } from 'lodash'
import { optionList, uatList } from '../index.schema'
import JiraNumberLink, { JiraNumberMixin } from '@/components/jira-number-link'
import { useDicts } from '@/components/storybook/hooks/useDict'
import ZTooltip from '@/components/storybook/z-tooltip'
import {
  fetchTag,
  fetchRole,
  fetchQuery,
  fetchAssignRole,
  fetchBot,
  matchJira,
  checkBotName,
  updateBot,
  deleteTag
} from '@/api/new'
import { symbolReg } from '@/components/storybook/utilties/reg'
import bus from '@/components/storybook/utilties/bus'

export default {
  name: 'EditBotForm',
  components: {
    JiraNumberLink,
    ZTooltip
  },
  mixins: [JiraNumberMixin],
  props: {
    resourceType: [String, Number],
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      form: {
        status: !this.$hasPermission('sys:bots:moreedit')
          ? 'Published'
          : 'Requested',
        businessType: this.$route.path.includes('CrossTenant')
          ? 'MSPbots Internal'
          : 'Custom',
        name: null,
        roleIdList: this.$store.state.defaultRoleList,
        description: null,
        newType: 0,
        tenantCode: this.$store.state.user.tenantCode,
        shared: false,
        applyTenant: false,
        teamId: '',
        classification: '',
        da: this.$store.state.user.id,
        po: '',
        jiraNumber: '',
        tagList: []
      },

      rules: {
        name: [
          { required: true, validator: this.validateName, trigger: 'blur' }
        ],
        roleIdList: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        // description: [
        //   { required: true, message: this.$t('validate.required'), trigger: 'blur' },
        // ],
        po: [
        //  {            required: true,            message: this.$t('validate.required'),            trigger: 'change'          }
        ],
        da: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'change'
          }
        ],
        jiraNumber: [
         // { required: true, validator: this.validateJira, trigger: 'blur' }
        ],
        businessType: [
          {
            required: false,
            message: this.$t('custom.tips.required', { fields: 'Type' }),
            trigger: 'change'
          }
        ],
        tenantCode: [
          {
            required: false,
            message: this.$t('custom.tips.required', { fields: 'Client' }),
            trigger: 'change'
          }
        ],
        status: [
          {
            required: true,
            message: this.$t('custom.tips.required', { fields: 'Status' }),
            trigger: 'change'
          }
        ]
      },

      loading: false,
      moreLoading: false,
      moreEditVisible: false,

      optionList,
      uatList,
      roles: [],
      tags: [],
      users: [],
      roleOptions: [],
      assignRoles: [],
      businessTypes: [],
      statusList: []
    }
  },
  computed: {
    classOptions() {
      return useDicts('bots_classification_list')
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      try {
        this.loading = true
        const [
          roles,
          tags,
          assignRoles,
          users,
          businessTypes,
          statusList,
          bot
        ] = await Promise.all([
          this.getRoles(),
          this.getTags(),
          this.getAssingRoles(),
          this.getUsers(),
          this.getBusinessTypes(),
          this.getStatusList(),
          this.getBot()
        ])
        this.roles = roles
        this.tags = tags
        this.users = users
        this.assignRoles = assignRoles
        this.statusList = statusList
        this.businessTypes = businessTypes
        const assigns = this.assignRoles.map(item => ({
          ...item,
          roleId: item.assignId
        }))
        this.roleOptions = intersectionBy(this.roles, assigns, 'roleId')
        try {
          let roleList = []
          for (var i = 0; i < bot.roleIdList.length; i++) {
            if (
              this.roleOptions.filter(
                item => item.roleId === bot.roleIdList[i]
              )[0]
            ) {
              roleList.push(bot.roleIdList[i])
              continue
            }
          }
          this.$set(bot, 'roleIdList', roleList)
        } catch (error) {
          
        }
        this.form = {
          ...this.form,
          ...bot
        }
      } catch (error) {
      } finally {
        this.loading = false
      }
    },

    async validateName(rule, value, callback) {
      if (!value) {
        throw new Error(this.$t('validate.required'))
      }
      try {
        const { name, id } = this.form
        let params = {
          name,
          id
        }
        if (!symbolReg.test(value)) {
          throw new Error(this.$t('validate.isIncludeSymbol'))
        }

        const { data: response } = await checkBotName(params)
        if (response.code !== 0) {
          throw new Error('The name is already exists')
        }
        callback()
      } catch (error) {
        callback(error)
      }
    },
    async validateJira(rule, value, callback) {
      try {
        if (!value) {
          throw new Error(this.$t('validate.required'))
        }

        let params = {
          issueIdOrKey: value
        }

        const isMatchJiraNumber = await matchJira(params)
        if (!isMatchJiraNumber) {
          throw new Error(this.$t('custom.component.gadget.checkNumber'))
        }
        callback()
      } catch (error) {
        callback(error)
      }
    },
    async getBusinessTypes() {
      const value = window.SITE_CONFIG['dictList'].find(
        e => e.dictType === 'datasets_type_list'
      )
      if (value) {
        const list = value.dataList || []
        if (
          this.form.businessType === 'MSPbots Internal' &&
          this.$hasPermission('sys:report:type:mspbots internal')
        ) {
          return list.filter(item => item.dictValue === 'MSPbots Internal')
        }

        return list.filter(item => item.dictValue !== 'MSPbots Internal')
      }
      return []
    },
    async getStatusList() {
      const value = window.SITE_CONFIG['dictList'].find(
        e => e.dictType === 'datasets_status_list'
      )
      if (value) {
        const list = value.dataList || []
        if (this.$hasPermission('sys:reports:publishauth')) {
          return list
        }

        return list.filter(
          item => item.dictValue !== 'Alpha' && item.dictValue !== 'Published'
        )
      }
      return []
    },
    async getRoles() {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      const { data: response } = await fetchRole(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getAssingRoles() {
      const roleIds = (this.$store.state.user.roleList || []).map(
        ({ id }) => id
      )
      const params = {
        roleId: roleIds
      }
      const { data: response } = await fetchAssignRole(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getTags() {
      const params = {}
      const { data: response } = await fetchTag(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    deleteTag(tag) {
      if (!tag) return false
      this.$confirm('Are you sure to delete?','warning', {
        type: 'warning',
      })
        .then(async () => {
          const params = {
            id: tag.id,
          }
          const { data: res } = await deleteTag(params)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.form.tagList = this.form.tagList&&this.form.tagList.filter(
            item => item!== tag.name
          )
          this.tags = await this.getTags()
          this.$message.success(res.msg)
          bus.$emit('update:tags', this.tags)
        })
    },
    async getUsers() {
      const params = {
        datasetKey: 'qwerdsafsadrtfzgsadfggs'
      }
      const { data: response } = await fetchQuery(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getBot() {
      const { data: response } = await fetchBot({ id: this.id })
      if (response.code !== 0) {
        return {}
      }
      return response.data || {}
    },

    async onSave() {
      try {
        this.moreEditVisible ? (this.moreLoading = true) : (this.loading = true)

        await this.$refs[this.moreEditVisible ? 'moreForm' : 'form'].validate()

        await this.validateForm()

        const { ...rest } = this.form
        const params = {
          ...rest,
          resourceType: this.resourceType
        }

        const { data: response } = await updateBot(params)
        if (response.code !== 0) {
          throw response.msg
        }
        if (response.data.exist) {
          throw this.$t('custom.dataset.nameexist')
        }
        this.$message.success(response.msg)
        this.$emit('event:success', response.data)
      } catch (error) {
        useErrorMessage(error)
      } finally {
        this.moreEditVisible
          ? (this.moreLoading = false)
          : (this.loading = false)
      }
    },
    async validateForm() {
      if (
        this.$store.state.user.username.includes('mspbots.ai') &&
        this.$hasPermission('sys:bots:moreedit')
      ) {
        const {
          da,
          po,
          jiraNumber,
          tenantCode,
          businessType,
          description,
          roleIdList,
          name,
          id
        } = this.form

        if (
          tenantCode === '1001' &&
          businessType === 'Custom' &&
          this.$store.state.user.tenantCode !== '1001'
        ) {
          throw 'The login person is the default tenant, then the type of widget cannot be Custom.'
        }

        if (!this.moreEditVisible) {
          if (!da) {
            throw this.$t('custom.component.gadget.da')
          }
          if (!po) {
            throw this.$t('custom.component.gadget.po')
          }
          if (jiraNumber !== 'NA') {
            let params = {
              issueIdOrKey: jiraNumber
            }

            const isMatchJiraNumber = await matchJira(params)
            if (!isMatchJiraNumber) {
              throw this.$t('custom.component.gadget.checkNumber')
            }
          }
        } else {
          if (!name) {
            throw 'Name ' + this.$t('validate.required')
          }
          if (!symbolReg.test(name)) {
            throw 'Name' + this.$t('validate.isIncludeSymbol')
          }

          let params = {
            name,
            id
          }

          const { data: response } = await checkBotName(params)
          if (response.code !== 0) {
            throw 'The name is already exists'
          }

          if (!roleIdList.length) {
            throw 'Role ' + this.$t('validate.required')
          }
          // if (!description) {
          //   throw 'Description ' + this.$t('validate.required')
          // }


        }
      }
    }
  }
}
</script>

<style lang="scss">
.more-dialog {
  .el-dialog__body {
    padding: 20px 0 20px 20px;
  }
}
.more-edit-dialog-form {
  height: 400px;
  padding-right: 15px;
  overflow: auto;
  .el-row {
    margin: 0;
  }

  &::-webkit-scrollbar {
    width: 5px;
    height: 5px;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: #17b3a3;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.4) 25%,
      rgba(255, 255, 255, 0.4)
    );
  }

  &::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
}
</style>
